const express = require('express')
const { crud, sequelizeCrud } = require('express-sequelize-crud')
const cookieParser = require('cookie-parser');
const http = require('http')
const cors = require('cors')

const moment = require('moment')

const Sequelize = require('sequelize');
const Op = Sequelize.Op

const bodyParser = require('body-parser');
let jsonParser = bodyParser.json()
let urlencodedParser = bodyParser.urlencoded({ extended: false })

const deviceApi = require('./api/device')
const { qrcodeApi } = require('./api/qrcode')

const {
    Device,
    HeartRateDetail,
    HeartRateMeasure,
    SleepDetail,
    Temperature,
    HRV,
    StepDetail,
    StepPerDay,
    addForeignKey,
    Gateway
} = require('./models')
addForeignKey()
const { loginHandler, loginVerify } = require('./login');


function trimObject(obj) {
    if (obj) {
        let attr = Object.keys(obj)
        for (let i = 0; i < attr.length; i++) {
            if (!obj[attr[i]]) {
                delete obj[attr[i]]
            }
        }
        return obj
    } else {
        return {}
    }
}

const customCrud = (Model) => {
    return {
        ...sequelizeCrud(Model),
        create: body => {
            return Model.create(trimObject(body))
        },
        update: (id, body) => {
            if (body.length > 0) {
                let record = body.find(item => item.id == id)
                // console.log(id, record)
                if (record) {
                    // console.log(id, record)
                    Model.update(trimObject(record), { where: { id } })
                    return record
                }
            } else {
                Model.update(body, { where: { id } })
                return body
            }
        },
        getList: ({ filter, limit, offset, order }) => {
            console.log('get list', filter, order)
            // filter.status = 0

            if (filter.date) {
                filter.startDate = filter.date
                filter.endDate = filter.date
            }
            if (filter.startDate && filter.endDate) {
                filter.date = {
                    // [Op.between]: [new Date(filter.startDate), moment(new Date(filter.endDate)).add(1, 'day').toDate()]
                    [Op.gte]: new Date(filter.startDate),
                    [Op.lt]: moment(new Date(filter.endDate)).add(1, 'day').toDate()
                }
                delete filter.startDate
                delete filter.endDate
            } else if (filter.startDate) {
                filter.date = {
                    [Op.gte]: new Date(filter.startDate)
                }
                delete filter.startDate
            } else if (filter.endDate) {
                filter.date = {
                    [Op.lt]: moment(new Date(filter.endDate)).add(1, 'day').toDate()
                }
                delete filter.endDate
            }
    
            return Model.findAndCountAll({
                limit, offset, order, where: filter
            })
        },

    }
}

/*
const cors = () => {
    return (req, res, next) => {
        // 允许任意源
        res.header('Access-Control-Allow-Origin', "*");
        // 允许的请求方法 修改请求头时会发送预检请求
        res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
        // 允许自定义头部
        res.header('Access-Control-Allow-Headers', "Token,Range");
        // 收到遇见请求返回成功状态
        if (req.method == 'OPTIONS') {
            res.header('Access-Control-Max-Age', 86400)
            res.sendStatus(204)
        } else {
            next();
        }
    }
}
*/

const app = new express()

const corsOptions = {
    origin: '*',
    method: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Accept', 'X-Requested-With', 'Cookie'],
    optionsSuccessStatus: 200, //Some legacy browsers (IE11, various SmartTVs) choke on 204,
    credentials: true
};

app.use(cookieParser())

app.use('/admin', cors({ maxAge: 86400 }), loginVerify, (req, res, next) => {
    console.log(req.body)
    // res.send('ooooops')
    next()
})

app.use(crud('/admin/gateway', customCrud(Gateway)))
app.use(crud('/admin/devs', customCrud(Device)))
app.use(crud('/admin/hr_detail', customCrud(HeartRateDetail)))
app.use(crud('/admin/hr_measure', customCrud(HeartRateMeasure)))
app.use(crud('/admin/sleep_detail', customCrud(SleepDetail)))
app.use(crud('/admin/temperature', customCrud(Temperature)))
app.use(crud('/admin/hrv', customCrud(HRV)))
app.use(crud('/admin/step_detail', customCrud(StepDetail)))
app.use(crud('/admin/step_per_day',customCrud(StepPerDay)))

app.use('/login', cors())
app.post('/login', loginHandler)


// app.use('/api', cors({ maxAge: 86400 }))
// app.use('/api/device', urlencodedParser, deviceApi)
// app.use('/api/qrcode', jsonParser, qrcodeApi)

app.use('/', express.static(__dirname + '/../client/build'))

// app.use('/', express.static(__dirname + '/web/build'))

var server = http.createServer(app);

server.listen(3001, () => {
    console.log('示例应用正在监听 3001 端口!');
});
